<template>
  <div>
    <el-table :data="dataSource" border>
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-row
            class="right_row"
            v-for="(item) in row.children"
            :key="item.id"
          >
            <el-col :span="4">
              <el-tag v-if="item.children && item.children.length != 0">{{
                item.authName
              }}</el-tag>
              <el-tag v-else closable @close="handleClose(row, item.id)">{{
                item.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row
                class="right_row"
                v-for="two in item.children"
                :key="two.id"
              >
                <el-col :span="4">
                  <el-tag
                    v-if="two.children && two.children.length != 0"
                    type="success"
                    >{{ two.authName }}</el-tag
                  >
                  <el-tag
                    v-else
                    closable
                    @close="handleClose(row, two.id)"
                    type="success"
                    >{{ two.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-row
                    class="right_row"
                    v-for="three in two.children"
                    :key="three.id"
                  >
                    <el-tag
                      type="danger"
                      closable
                      @close="handleClose(row, three.id)"
                      >{{ three.authName }}</el-tag
                    >
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="roleName" label="角色名称">
         <template #default="{row}">
          <div v-show="!row.flag">{{row.roleName}}</div>
          <el-input v-show="row.flag" type="text" v-model="row.roleName" size="small"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述">
        <template #default="{row}">
          <div v-show="!row.flag">{{row.roleDesc}}</div>
          <el-input v-show="row.flag" type="text" v-model="row.roleDesc" size="small"></el-input>
        </template>
      </el-table-column>
      <el-table-column>
        <template slot="header">
          <el-button type="primary"
          @click="tianjiaVisible=true"
          >添加</el-button>
        </template>
        <el-table-column label="操作">
          <template #default="{ row }">
          <el-button @click="goEdite(row)" size="small" type="primary" icon="el-icon-edit"
              >{{row.flag?'完成':'修改'}}</el-button
            >
            <el-button size="small" type="danger" icon="el-icon-delete" @click="del(row.id)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="warning"
              icon="el-icon-s-tools"
              @click="goSetRight(row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <el-dialog title="提示" :visible.sync="setRightDialog" width="50%">
      <!--node-key ：指定复选框绑定的属性-->
      <el-tree
        :data="treeData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button @click="resetChecked">清空</el-button>
        <el-button @click="setAll">全选</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
   <el-dialog title="提示" :visible.sync="tianjiaVisible" width="30%">
      <el-form 
      label-width="100px"
      size="small"
      style="width:270px"
      :model="abcObj"
      ref="ruleForm">
       <el-form-item label="角色名称:">
            <el-input type="text" v-model="abcObj.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述:">
            <el-input type="text" v-model="abcObj.roleDesc"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="tianjiaVisible = false">取 消</el-button>
          <el-button type="primary" @click="doupdate()">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>


<script>
import {
  api_role_query,
  api_serRight,
  api_delteRight,
} from "../../api/role.js";
import { api_getRight } from "../../api/right.js";
import { api_dels,api_userss,api_update } from '../../api/user.js';
import request from "../../utils/reuqest.js"
export default {
  data() {
    request
    return {
  
     tianjiaVisible: false,
      dataSource: [],
      setRightDialog: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      abcObj: {
        roleName: "",
        roleDesc: "",
       
      },
      
      rightIds: [],
      roleId: 0,
      allId: [],
    };
  },
  mounted() {
    this.query();
  },
  methods: {
    // 查询
    async query() {
      let rst = await api_role_query();
      let { data } = rst;
      this.dataSource = data;
      data.forEach((item)=>{
        this.$set(item,'flag',false)
      })
    },
// 删除
async del(id){
  console.log(id);
this.$confirm('此操作将永久删除该用户,是否继续','提示',{
  confirmButtonText:'确定',
  cancelButtonText:'取消',
  type:'danger'
}).then(async()=>{
  let rst=await api_dels({id})
  console.log(rst);
  if(rst.meta.status==200){
    this.query();
  }else{
    this.$message.error("删除失败")
  }

}).catch(()=>{
  this.$message.info("已取消删除")
})

},
// 添加角色
 doupdate() {
      this.$refs.ruleForm.validate(async (b) => {
        if (b) {
          let rst = await api_userss(this.abcObj);
          console.log(rst);
          let {status,msg } = rst.meta;
          if (status = 201) {
            this.tianjiaVisible = false;
            this.$message.success(msg);
            this.query();
            this.abcObj = {};
          }
        }
    })
    },
    // 修改
    async goEdite(row){
if(row.flag){
let rst=await api_update({id:row.id,roleName:row.roleName,roleDesc:row.roleDesc})
console.log(rst);
let {status}=rst.meta;
if(status==200){
  let {roleName}=rst.data;
  this.$message.success(`用户:${roleName}"修改成功"`);
}
}
row.flag =!row.flag;
    },
    async goSetRight(row) {
    this.setRightDialog = true;
      this.rightIds = [];
      this.goSetRightDialog = true;
      this.roleId = row.id;
      let rst = await api_getRight({ url: "tree" });
      this.treeData = rst.data;
      console.log(this.treeData);
      this.setRightId(row, this.rightIds);
      const treeAllObj = {
        children: [],
      };
      treeAllObj.children = rst.data;
      this.setRightId(treeAllObj, this.allId);
      this.$refs.tree.setCheckedKeys(this.rightIds);
    },
    setRightId(obj, arr) {
      if (!obj.children) {
        arr.push(obj.id);
        return;
      }
      obj.children.forEach((item) => {
        this.setRightId(item, arr);
      });
    },
    async setRight() {
       let halfkeys = this.$refs.tree.getHalfCheckedKeys();
      let currentKeys = this.$refs.tree.getCheckedKeys();
      let rids = [...halfkeys, ...currentKeys].join(",");
      let rst = await api_serRight({ roleId: this.roleId, rids });
      if (rst.meta.status == 200) {
        this.setRightDialog = false;
        this.query();
      }
    },
    async handleClose(row, rightId) {
      console.log("row", row);
      console.log("rightId", rightId);
      let rst = await api_delteRight({ roleId: row.id, rightId });
      if (rst.meta.status == 200) {
        row.children = rst.data;
        console.log(rst.data);
      }
      console.log(rst);
    },
    // 清空复选框的函数
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    //全选
    setAll() {
      this.$refs.tree.setCheckedKeys(this.allId);
    },
  },
};
</script>

<style lang="less" scoped>
</style>